package ntd.block.file;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.block.file.bo.ComDiskFileBO;
import ntd.util.UtilCatch;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 磁盘文件工具
 */
public class ComDiskFile {

    private String basePath = "D://work-file";

    public void init() {

    }

    public List<ComDiskFileBO> treeList(String path) {
        return CollStreamUtil.toList(FileUtil.loopFiles(path), ComDiskFileBO::transform);
    }

    public List<ComDiskFileBO> tree() {
        return tree(basePath);
    }

    public List<ComDiskFileBO> tree(String path) {
        StaticLog.info("扫描路径 - {}", path);
        ArrayList<File> files = ListUtil.toList(FileUtil.ls(path));
        CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(files.size());
        List<ComDiskFileBO> comDiskFileBOS = CollStreamUtil.toList(files, file -> {
            ComDiskFileBO comDiskFileBO = ComDiskFileBO.transform(file);
            if (comDiskFileBO.isDir()) {
                comDiskFileBO.setChildren(tree(comDiskFileBO.getPath()));
            }
            countDownLatch.countDown();
            return comDiskFileBO;
        });
        UtilCatch.tryCatchNoRes(countDownLatch::await);
        return comDiskFileBOS;
    }

    public static void main(String[] args) {
        ComDiskFile comDiskFile = new ComDiskFile();
        List<ComDiskFileBO> tree = comDiskFile.treeList(comDiskFile.basePath);
        for (ComDiskFileBO comDiskFileBO : tree) {
            StaticLog.info(JSONUtil.toJsonStr(comDiskFileBO));
        }
    }
}
